package com.ruoyi.cs.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.banbeiPay.Disguiser;
import com.ruoyi.common.banbeiPay.HttpClientService;
import com.ruoyi.common.banbeiPay.MyBeanUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.payment.SanjinConstants;
import com.ruoyi.common.payment.YukuaiqiConstants;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.Base64;
import com.ruoyi.common.utils.bean.QueryOrderResponseVo;
import com.ruoyi.common.utils.bean.QueryOrderVo;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.pay.*;
import com.ruoyi.cs.domain.HCPayQueryOrder;
import com.ruoyi.cs.domain.TRecharge;
import com.ruoyi.cs.mapper.TRechargeMapper;
import com.ruoyi.cs.service.CommonService;
import com.ruoyi.cs.service.IRechargeTaskService;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.util.*;

/**
 * 充值定时任务公共类
 */
@Service
@SuppressWarnings("all")
public class RechargeTaskServiceImpl implements IRechargeTaskService {

    private static final Logger log = LoggerFactory.getLogger(RechargeTaskServiceImpl.class);

    @Autowired
    private CommonService commonService;

    @Autowired
    private TRechargeMapper tRechargeMapper;

    /**
     * 聚合支付
     * @param list
     * @param pollingNum
     */
    @Override
    public void expireTRecharge(List<TRecharge> list, int pollingNum) {
        log.info("聚合支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    Map<String, String> payData = new HashMap<>();
                    payData.put("version", "1.0");
                    payData.put("customerid", PayjsConfig.customerid);
                    payData.put("sdorderno", tRecharge.getCzId());
                    payData.put("sign", SignUtils.signQueryOrderJH(payData, PayjsConfig.apikey));
                    String result = HttpUtils.http(PayjsConfig.ORDER_QUERY_URL, payData);
                    if (result != null) {
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("聚合充值订单轮询");

                        if (!result.contains("<html>")) {
                            JSONObject josnResult = JSON.parseObject(result);
                            Integer status = josnResult.getInteger("status");
                            if (status != null) {
                                /**交易完成、支付成功*/
                                if (status == 0) {
                                    tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                    tRecharge.setCzStatus(Constants.CZSTATUS1);
                                    tRecharge.setRemark("聚合充值订单轮询交易成功");
                                    flag = true;
                                } else if (status == 3 || status == 4 || status == 5) {
                                    /**交易关闭*/
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    tRecharge.setRemark("聚合充值订单轮询交易关闭");
                                } else {
                                    /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                    if (tRecharge.getQueryNum() > pollingNum) {
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    }
                                    tRecharge.setRemark("聚合充值订单轮询" + tRecharge.getQueryNum() + "次");
                                }
                            } else {
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("聚合充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + status);
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("聚合充值订单轮询" + tRecharge.getQueryNum() + "次，result包含html标签");
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("聚合支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("聚合支付成功定时处理订单个数:{}", countnum);
        }
    }

    /**
     * 汇潮支付
     * @param list
     * @param pollingNum
     */
    @Override
    public void expireHCRecharge(List<TRecharge> list, int pollingNum) {
        log.info("汇潮支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                HCPayQueryOrder hcPayQueryOrder = new HCPayQueryOrder();
                hcPayQueryOrder.setMerCode(CompanyConfig.HC_MERCHANTNO);
                hcPayQueryOrder.setOrderNumber(tRecharge.getCzId());
                String beginTime = DateFormatUtils.format(tRecharge.getCreateTime(), "yyyyMMddHHmmss");
                String endTime = DateUtils.fewMinutesLater(tRecharge.getCreateTime(), 10) == null ? beginTime : DateUtils.fewMinutesLater(tRecharge.getCreateTime(), 10);
                hcPayQueryOrder.setBeginTime(beginTime);
                hcPayQueryOrder.setEndTime(endTime);
                hcPayQueryOrder.setPageIndex("1");
                String signContent = hcPayQueryOrder.getMerCode();
                //签名
                String sign = null;
                try {
                    sign = RSAutil.sign(signContent, RSAutil.getPrivateKey(CompanyConfig.HCPAY_PRIKEY));
                    hcPayQueryOrder.setSign(sign);
                    System.out.println("sign:" + sign);
                    hcPayQueryOrder.setTx(CompanyConfig.HCPAY_TX_1001);
                    /**
                     * 拼接成Xml明文
                     */
                    XStream xStream = new XStream();
                    xStream.alias("root", HCPayQueryOrder.class);
                    xStream.useAttributeFor(HCPayQueryOrder.class, "tx");
                    String requestDomain = xStream.toXML(hcPayQueryOrder);
                    //Xml明文进行Base64编码
                    requestDomain = Base64.encode("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + requestDomain);
                    HttpsClient client = new HttpsClient(CompanyConfig.HCPAY_QUERY_URL);
                    client.addParam("requestDomain", requestDomain);
                    String result = client.sendHttps(10000);
                    log.info("调用汇潮查询接口响应：{}", result);
                    if (result != null) {
                        boolean flag = false;/**表示是否交易完成*/
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("汇潮充值订单轮询");
                        if (result.contains("<?xml")) {
                            JSONObject resultJson = parsingXml(result);
                            String orderStatus = resultJson.getString("orderStatus");
                            String resultCode = resultJson.getString("resultCode");

                            if (CompanyConfig.RESULTCODE_00.equals(resultCode)) {
                                if (StringUtils.isNotEmpty(orderStatus)) {
                                    /*0失败，1成功，3处理中*/
                                    /**交易完成、支付成功*/
                                    if (orderStatus.equals("1")) {
                                        tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                        tRecharge.setCzStatus(Constants.CZSTATUS1);
                                        tRecharge.setRemark("汇潮充值订单轮询交易成功");
                                        flag = true;
                                    } else if (orderStatus.equals("0")) {
                                        /**交易关闭*/
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                        tRecharge.setRemark("汇潮充值订单轮询交易关闭");
                                    } else {
                                        /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                        if (tRecharge.getQueryNum() > pollingNum) {
                                            tRecharge.setCzStatus(Constants.CZSTATUS2);
                                        }
                                        tRecharge.setRemark("汇潮充值订单轮询" + tRecharge.getQueryNum() + "次");
                                    }
                                } else {
                                    if (tRecharge.getQueryNum() > pollingNum) {
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    }
                                    tRecharge.setRemark("汇潮充值订单轮询orderStatus为空");
                                }
                            } else {
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("汇潮充值订单轮询" + tRecharge.getQueryNum() + "次，orderStatus：" + resultCode);
                                log.error("汇潮支付查询订单接口请求失败：订单号：{}，状态码：{}", tRecharge.getCzId(), resultCode);
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("汇潮充值订单轮询，汇潮订单查询接口响应不为XML格式");
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("汇潮支付查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("汇潮支付成功定时处理订单个数:{}", countnum);
        }
    }

    /**
     * 传化支付
     * @param list
     * @param pollingNum
     */
    @Override
    public void expireCHRecharge(List<TRecharge> list, int pollingNum) {
        log.info("传化支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                TreeMap<String, String> map = new TreeMap<String, String>();
                map.put("mch_id", CHPayConfig.mch_id);                          //必填 商户编号
                map.put("out_trade_no",tRecharge.getCzId());           //必填 商户订单号
                map.put("sign", SignUtils.buildSign(map, CHPayConfig.key));               //必填 签名参数
                log.info("【传化查询请求参数】：" + map.toString());
                //签名
                try {
                    String str = HttpUtils.http(CHPayConfig.orderquery, map);
                    log.info("【传化查询返回参数】：" + str);
                    if (StringUtils.isNotEmpty(str)) {
                        boolean flag = false;/**表示是否交易完成*/
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("传化充值订单轮询");

                        JSONObject result  = JSON.parseObject(str);
                        JSONObject signObj =  result.getJSONObject("params_info");
                        String payFrom = signObj.getString("pay_info");
                        String order_status = signObj.getString("order_status");
                        String sign = result.getString("sign");
                        String resultCode = result.getString("return_code");
                        String returnMsg = result.getString("return_msg");

                        JSONObject paramsMap = new JSONObject();
                        paramsMap.put("mch_id", signObj.getString("mch_id"));
                        paramsMap.put("order_no", signObj.getString("order_no"));
                        paramsMap.put("out_trade_no", signObj.getString("out_trade_no"));
                        paramsMap.put("total_fee", signObj.getString("total_fee"));
                        paramsMap.put("trade_type", signObj.getString("trade_type"));
                        paramsMap.put("order_status", signObj.getString("order_status"));
                        paramsMap.put("order_status_desc", signObj.getString("order_status_desc"));

                        String paramsStr = SignUtils.getSortJson(paramsMap);
                        String mchSign = SignUtils.buildStrSign(paramsStr, CHPayConfig.key);
                        if (mchSign.equals(sign)) {
                            log.info("【传化查询返回验签成功】：" + str);
                            if ("0".equals(resultCode)) {
                                if (StringUtils.isNotEmpty(order_status)) {
                                    BigDecimal fee = tRecharge.getCzMoney().multiply(new BigDecimal(6.5)).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                                    if(fee.compareTo(new BigDecimal(signObj.getString("total_fee"))) == 0){
                                        /**交易完成、支付成功*/
                                        if (order_status.equals("2")) {
                                            tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                            tRecharge.setCzStatus(Constants.CZSTATUS1);
                                            tRecharge.setRemark("传化支付订单轮询交易成功");
                                            flag = true;
                                        }  else {
                                            /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                            if (tRecharge.getQueryNum() > pollingNum) {
                                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                                            }
                                            tRecharge.setRemark("传化充值订单轮询" + tRecharge.getQueryNum() + "次");
                                        }
                                    }else {
                                        /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                        if (tRecharge.getQueryNum() > pollingNum) {
                                            tRecharge.setCzStatus(Constants.CZSTATUS2);
                                        }
                                        tRecharge.setRemark("传化充值金额不匹配");
                                    }
                                } else {
                                    if (tRecharge.getQueryNum() > pollingNum) {
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    }
                                    tRecharge.setRemark("传化支付充值订单轮询order_status为空");
                                }
                            } else {
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("传化支付订单轮询" + tRecharge.getQueryNum() + "次，orderStatus：" + resultCode+" ,msg: "+returnMsg);
                                log.error("传化支付订单轮询接口返回失败信息：订单号：{}，状态码：{}，错误信息:{}", tRecharge.getCzId(), resultCode,returnMsg);
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("传化支付订单轮询，查询接口验签不通过！");
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("传化支付调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("传化支付查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("传化支付成功定时处理订单个数:{}", countnum);
        }
    }

    /**
     * 宝和利支付
     * @param list
     * @param pollingNum
     */
    @Override
    public void expireBHLRecharge(List<TRecharge> list, int pollingNum) {
        log.info("宝和利支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                boolean flag = false;
                try {
                    QueryOrderVo queryOrderVo = this.createQueryOrderParam(tRecharge.getCzId());
                    Map<String, String> map = MyBeanUtils.convertBean(queryOrderVo, new LinkedHashMap());
                    String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, QueryOrderVo.NEED_SIGN_PARAMS, false);
                    String sign = Disguiser.disguiseMD5(oriMessage.trim());
                    map.put("sign", sign);
                    Map<String, Object> resultMap = HttpClientService.getHttpResp(map, Constants.REQUEST_URL);
                    if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("宝和利充值订单轮询");

                        String resultMsg = (String) resultMap.get("response");
                        QueryOrderResponseVo queryOrderResponseVo = JSONObject.parseObject(resultMsg, QueryOrderResponseVo.class);
                        String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(queryOrderResponseVo, QueryOrderResponseVo.NEED_SIGN_PARAMS, false);
                        String responseSign = queryOrderResponseVo.getSign();
                        String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                        if (checkSign.equals(responseSign)) {
                            if ("0000".equals(queryOrderResponseVo.getRt2_retCode())) {
                                log.info("宝和利支付订单查询接口请求成功");
                                String rt7OrderStatus = queryOrderResponseVo.getRt7_orderStatus();
                                if (Constants.BHL_SUCCESS.equalsIgnoreCase(rt7OrderStatus)) {
                                    tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                    tRecharge.setCzStatus(Constants.CZSTATUS1);
                                    tRecharge.setRemark("宝和利订单轮询交易成功");
                                    flag = true;
                                } else if (Constants.BHL_FAIL.equalsIgnoreCase(rt7OrderStatus) || Constants.BHL_CLOSE.equalsIgnoreCase(rt7OrderStatus) || Constants.BHL_CANCEL.equalsIgnoreCase(rt7OrderStatus)) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    tRecharge.setRemark("宝和利充值订单轮询交易关闭");
                                } else {
                                    if (tRecharge.getQueryNum() > pollingNum) {
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    }
                                    tRecharge.setRemark("宝和利订单轮询" + tRecharge.getQueryNum() + "次");
                                }
                            }else {
                                log.error("宝和利订单查询结果错误:{}", queryOrderResponseVo.getRt3_retMsg());
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("宝和利订单查询结果错误:"+ queryOrderResponseVo.getRt3_retMsg());
                            }
                        }else {
                            log.error("宝和利订单查询结果验签不通过:{},签名:{]", resultMsg, checkSign);
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("宝和利支付订订单轮询，查询接口验签不通过！");
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    }else {
                        log.error("宝和利查询订单接口请求失败,查询结果参数:{}", resultMap);
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch(Exception e){
                    log.error("宝和利支付查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
                log.info("传宝和利支付成功定时处理订单个数:{}", countnum);
            }
        }
    }

    /**
     * 富信支付过期处理
     * @param list
     * @param pollingNum
     */
    @Override
    public void expireFuXinRecharge(List<TRecharge> list, int pollingNum) {
        log.info("富信支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    Map<String, String> payData = new HashMap<>();
                    payData.put("sdorderno", tRecharge.getCzId());
                    payData.put("appid", FXPayConfig.applyId);
                    Integer goodsId = CommonUtils.getCzGoodsId(Constants.CZGOODSID,tRecharge.getCzMoney());
                    payData.put("goods_id", goodsId.toString());
                    payData.put("sign", SignUtils.signFXQuery(payData, FXPayConfig.applykey));
                    String result = HttpUtils.http(FXPayConfig.applyQuery,payData);
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (jsonObject != null) {
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("富信支付充值订单轮询");

                        Integer status = jsonObject.getInteger("status");
                        if (status != null) {
                            /**交易完成、支付成功*/
                            if (status == 1) {
                                tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                tRecharge.setCzStatus(Constants.CZSTATUS1);
                                tRecharge.setRemark("富信支付充值订单轮询交易成功");
                                flag = true;
                            } else if (status == 2) {
                                /**交易关闭*/
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                                tRecharge.setRemark("富信支付充值订单轮询交易关闭");
                            } else {
                                /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("富信支付充值订单轮询" + tRecharge.getQueryNum() + "次");
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("富信支付充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + status);
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("富信支付调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("聚富信支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("富信支付成功定时处理订单个数:{}", countnum);
        }
    }

    @Override
    public void expireJiuJiaRecharge(List<TRecharge> list, int pollingNum) {
        log.info("九嘉支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    Map<String, String> payData = new HashMap<>();
                    payData.put("app_key", Constants.app_key);
                    payData.put("out_trade_no", tRecharge.getPlatformOrderNo());
                    payData.put("member_id", Constants.member_id);
                    String result = HttpUtils.http("https://zhifu.jiujiaka.com/alipay/check_pay2",payData);
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (jsonObject != null && jsonObject.getString("code").equals("0")) {
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("九嘉支付充值订单轮询");

                        String status = jsonObject.getJSONObject("data").getString("status");
                        if (status != null) {
                            /**交易完成、支付成功*/
                            if ("TRADE_SUCCESS".equalsIgnoreCase(status) || "TRADE_FINISHED".equalsIgnoreCase(status)) {
                                tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                tRecharge.setCzStatus(Constants.CZSTATUS1);
                                tRecharge.setRemark("九嘉支付充值订单轮询交易成功");
                                flag = true;
                            } else if ("TRADE_CLOSED".equalsIgnoreCase(status)) {
                                /**交易关闭*/
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                                tRecharge.setRemark("九嘉支付充值订单轮询交易关闭");
                            } else {
                                /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("九嘉支付充值订单轮询" + tRecharge.getQueryNum() + "次");
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("九嘉支付充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + status);
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("九嘉支付调用接口响应为空");
                        if(jsonObject != null){
                            tRecharge.setRemark(jsonObject.getString("msg"));
                        }
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("九嘉支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("九嘉支付成功定时处理订单个数:{}", countnum);
        }
    }

    @Override
    public void expireYmyRecharge(List<TRecharge> list, int pollingNum) {
        log.info("优米云支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    Map<String, String> payData = new HashMap<>();
                    payData.put("version", "1.0");
                    payData.put("customerid", PayjsConfig.customerid);
                    payData.put("sdorderno", tRecharge.getCzId());
                    payData.put("sign", SignUtils.signQueryOrderJH(payData, PayjsConfig.apikey));
                    String result = HttpUtils.http(PayjsConfig.orderQueryUrl, payData);
                    if (result != null){
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("优米云支付充值订单轮询");
                        if (!result.contains("<html>")) {
                            JSONObject josnResult = JSON.parseObject(result);
                            Integer status = josnResult.getInteger("status");
                            if (status != null) {
                                /**交易完成、支付成功*/
                                if (status == 0 || status == 2) {
                                    tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                    tRecharge.setCzStatus(Constants.CZSTATUS1);
                                    tRecharge.setRemark("优米云支付充值订单轮询交易成功");
                                    flag = true;
                                }else if (status ==  1){
                                    /**交易关闭*/
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    tRecharge.setRemark("查询订单,未付款");
                                } else if (status == 3 || status == 4 || status == 5 || status == 6) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    tRecharge.setRemark("查询订单,交易关闭");
                                }else {
                                    /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                    if (tRecharge.getQueryNum() > pollingNum) {
                                        tRecharge.setCzStatus(Constants.CZSTATUS2);
                                    }
                                    tRecharge.setRemark("优米云支付充值订单轮询" + tRecharge.getQueryNum() + "次");
                                }
                            } else {
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("优米云支付充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + status);
                            }
                            commonService.czquerySuccess(tRecharge, flag);
                        }else {
                            tRecharge.setRemark("定时任务,result包含html标签,直接设置充值失败");
                            this.czfail(tRecharge, pollingNum);
                        }
                    } else {
                        tRecharge.setRemark("优米云支付调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("优米云支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("优米云支付成功定时处理订单个数:{}", countnum);
        }
    }

    @Override
    public void expireYukuaiqiRecharge(List<TRecharge> list, int pollingNum) {
        log.info("yukuaiqi支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    Map<String, String> payData = new HashMap<>();
                    payData.put("openid", YukuaiqiConstants.openid);
                    payData.put("out_trade_no", tRecharge.getCzId());
                    payData.put("total_fee", tRecharge.getCzMoney().toString());
                    payData.put("nonce_str", tRecharge.getCzId());
                    String toBeSigned = "nonce_str=" +tRecharge.getCzId() +
                            "&openid=" + YukuaiqiConstants.openid +
                            "&out_trade_no=" + tRecharge.getCzId() +
                            "&total_fee=" + tRecharge.getCzMoney().toString() +
                            "&key=" + YukuaiqiConstants.key;

                    // 使用MD5进行加密，并转换为大写形式
                    String sign = DigestUtils.md5Hex(toBeSigned).toUpperCase();
                    payData.put("sign",sign);
                    /**发送请求*/
                    HttpResponse response = HttpRequest.post(YukuaiqiConstants.orderQueryUrl)
                            .header("Content-Type", "application/json")
                            .body(JSON.toJSONString(payData))
                            .execute();

                    // 获取响应内容
                    String result = response.body();
                    if (result != null){
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("yukuaiqi支付充值订单轮询");

                        JSONObject josnResult = JSON.parseObject(result);
                        Integer code = josnResult.getInteger("code");
                        if (code != null) {
                            /**交易完成、支付成功*/
                            if (code == 0) {
                                tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                tRecharge.setCzStatus(Constants.CZSTATUS1);
                                tRecharge.setRemark("yukuaiqi支付充值订单轮询交易成功");
                                flag = true;
                            }
//                            else if (code ==  1){
//                                /**交易关闭*/
//                                tRecharge.setCzStatus(Constants.CZSTATUS2);
//                                tRecharge.setRemark("查询订单,未付款");
//                            }
                            else {
                                /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("yukuaiqi支付充值订单轮询" + tRecharge.getQueryNum() + "次");
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("yukuaiqi支付充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + code);
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("yukuaiqi支付调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("yukuaiqi支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("yukuaiqi支付成功定时处理订单个数:{}", countnum);
        }
    }

    @Override
    public void expireSanjinRecharge(List<TRecharge> list, int pollingNum) {
        log.info("sanjin支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (list != null && list.size() > 0) {
            int countnum = 0;
            for (TRecharge tRecharge : list) {
                try {
                    MultiValueMap<String,Object> map= new LinkedMultiValueMap<>();
                    String reqtime = String.valueOf(System.currentTimeMillis()/1000);
                    String signStr = "customerid=" + SanjinConstants.customerId + "&sdorderno=" + tRecharge.getCzId() + "&reqtime=" + reqtime;
                    String sign = SanjinDemoUtils.encryptToMD5(signStr +"&"+ SanjinConstants.key);
                    map.add("customerid",SanjinConstants.customerId);
                    map.add("sdorderno",tRecharge.getCzId());
                    map.add("reqtime",reqtime);
                    map.add("sign",sign);
                    Map<String, Object> resMap = SanjinDemoUtils.postFormData(map, SanjinConstants.queryUrl);

                    if (resMap != null){
                        /**表示是否交易完成*/
                        boolean flag = false;
                        tRecharge.setUpdateTime(DateUtils.getNowDate());
                        tRecharge.setQueryNum(tRecharge.getQueryNum() + 1);
                        tRecharge.setRemark("sanjin支付充值订单轮询");

                        Integer status = (Integer)resMap.get("status");
                        if (status != null) {
                            /**交易完成、支付成功*/
                            if (status == 1) {
                                tRecharge.setCzSuccTime(DateUtils.getNowDate());
                                tRecharge.setCzStatus(Constants.CZSTATUS1);
                                tRecharge.setRemark("sanjin支付充值订单轮询交易成功");
                                flag = true;
                            } else {
                                /**交易创建中  如果查询订单次数超过设定的轮询次数，则直接定为交易失败*/
                                if (tRecharge.getQueryNum() > pollingNum) {
                                    tRecharge.setCzStatus(Constants.CZSTATUS2);
                                }
                                tRecharge.setRemark("sanjin支付充值订单轮询" + tRecharge.getQueryNum() + "次");
                            }
                        } else {
                            if (tRecharge.getQueryNum() > pollingNum) {
                                tRecharge.setCzStatus(Constants.CZSTATUS2);
                            }
                            tRecharge.setRemark("sanjin支付充值订单轮询" + tRecharge.getQueryNum() + "次，status：" + status);
                        }
                        commonService.czquerySuccess(tRecharge, flag);
                    } else {
                        tRecharge.setRemark("sanjin支付调用接口响应为空");
                        this.czfail(tRecharge, pollingNum);
                    }
                    countnum++;
                } catch (Exception e) {
                    log.error("sanjin支付宝查询订单接口异常：订单号：{}，异常说明：{}", tRecharge.getCzId(), e.getMessage());
                }
            }
            log.info("sanjin支付成功定时处理订单个数:{}", countnum);
        }
    }

    public void czfail(TRecharge tRecharge, Integer pollingNum) {
        TRecharge tRecharge1 = new TRecharge();
        tRecharge1.setCzId(tRecharge.getCzId());
        tRecharge1.setRemark(tRecharge.getRemark());
        tRecharge1.setUpdateTime(DateUtils.getNowDate());
        tRecharge1.setQueryNum(tRecharge.getQueryNum() + 1);

        if (tRecharge1.getQueryNum() > pollingNum) {
            tRecharge1.setCzStatus(Constants.CZSTATUS2);
        }
        tRechargeMapper.updateTRechargeNotify(tRecharge1);
    }

    /**
     * 解析响应报文
     *
     * @param resMsgXml 响应报文xml
     * @return
     * @throws Exception
     */
    private static JSONObject parsingXml(String resMsgXml) throws Exception {

        /*将字符串转为XML*/
        Document doc = DocumentHelper.parseText(resMsgXml);
        /*获取根节点*/
        Element rootElt = doc.getRootElement();
        /*获取根节点下的子节点resultCode*/
        Iterator iter = rootElt.elementIterator("resultCode");
        Element resultCode_node = (Element) iter.next();
        String resultCode = resultCode_node.getText();
        /*获取根节点下的子节点list*/
        Iterator list_node = rootElt.elementIterator("list");
        JSONObject jsonObject = new JSONObject();
        if (list_node.hasNext()) {
            Element status = (Element) list_node.next();
            String orderStatus = status.elementTextTrim("orderStatus");
            jsonObject.put("orderStatus", orderStatus);
        }
        jsonObject.put("resultCode", resultCode);

        return jsonObject;
    }

    /**组装宝和利支付订单查询参数*/
    public QueryOrderVo createQueryOrderParam(String orderid){
        QueryOrderVo orderVo = new QueryOrderVo();
        orderVo.setP1_bizType("AppPayQuery");
        orderVo.setP2_orderId(orderid);
        orderVo.setP3_customerNumber(Constants.PA_MERCHANT_NO);
        return orderVo;
    }
}
